﻿using StarPizza.Model.BaseModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarPizza.Model.Core
{
    public class Catalogue
    {
        StarDataDataContext db;
        IIngredientResource ingredientResource;

        public delegate void AvailablePizzasChangedEventHandler();
        public event AvailablePizzasChangedEventHandler AvailablePizzasChanged;
        public event Action<PizzaTemplate> NewPizzaAdded;

        public Catalogue(StarDataDataContext db, IIngredientResource ingredientResource)
        {
            this.db = db;
            this.ingredientResource = ingredientResource;
            ingredientResource.OutOfTopping += stockHandler_OutOfTopping;
            ingredientResource.ToppingBecameAvailable += stockHandler_ToppingBecameAvailable;
        }
        void stockHandler_ToppingBecameAvailable(Topping topping)
        {
            if (AvailablePizzasChanged != null)
                AvailablePizzasChanged();
        }
        void stockHandler_OutOfTopping(Topping topping)
        {
            if (AvailablePizzasChanged != null) 
                AvailablePizzasChanged();
        }
        public void AddPizzaTemplate(PizzaTemplate pizzaTemplate)
        {
            db.PizzaTemplate.InsertOnSubmit(pizzaTemplate);
            Utility.TrySubmitChanges(db);
            if (AvailablePizzasChanged != null)
                AvailablePizzasChanged();
            if (NewPizzaAdded != null)
                NewPizzaAdded(pizzaTemplate);
        }
        public List<PizzaTemplate> GetAllPizzas()
        {
            return db.PizzaTemplate.ToList();
        }
        public bool IsPizzaTemplateOrderable(PizzaTemplate pizzaTemplate)
        {
            return
                pizzaTemplate.IsActive &&
                ingredientResource.IsPizzaTemplateOrderable(pizzaTemplate);
        }
        public void UpdatePizzaTemplates()
        {
            Utility.TrySubmitChanges(db);
            AvailablePizzasChanged();
        }
    }
}
